package nodes.visitor;

import org.jdom.Element;

import nodes.ConstNode;
import nodes.FuncNode;
import nodes.Node;
import nodes.ParamNode;

public class XMLNodeVisitor implements NodeVisitor {
	
	private Element root = new Element("tree");
	private Element current = root;

	public Element getRoot() {
		return root;
	}
	
	public void reset() {
		root = new Element("tree");
		current = root;
	}
	
	@Override
	public void visitConstNode(ConstNode<?> node) {
		Element element = new Element("const");
		element.setAttribute("value", "" + node.getValue());
		current.addContent(element);
	}

	@Override
	public void visitFuncNode(FuncNode<?> node) {
		Element element = new Element("func");
		element.setAttribute("name", node.getName());
		current.addContent(element);
		Element previous = current;
		current = element;
		
		for(Node<?> child : node.getChildren())
			child.accept(this);
		
		current = previous;
	}

	@Override
	public void visitParamNode(ParamNode<?> node) {
		Element element = new Element("param");
		element.setAttribute("index", "" + node.getParam());
		current.addContent(element);
	}
}
